package com.itcms.core.service.impl;

import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itcms.core.domain.Info;
import com.itcms.core.domain.NodeExt;
import com.itcms.core.domain.NodeExt.NodeExtId;
import com.itcms.core.domain.Node;
import com.itcms.core.repository.NodeExtDao;
import com.itcms.core.service.NodeExtService;
import com.itcms.core.service.NodeQueryService;

@Service
@Transactional(readOnly = true)
public class NodeExtServiceImpl implements NodeExtService {
	private NodeExt findOrCreate(Node node, Node nodeExt) {
		NodeExt bean = dao.findOne(new NodeExtId(node.getId(), nodeExt.getId()));
		if (bean == null) {
			bean = new NodeExt(node, nodeExt);
		}
		return bean;
	}

	@Transactional
	public List<NodeExt> update(Node node, Integer[] nodeIds, Integer nodeId) {
		// 主栏目为null，不更新。
		if (nodeId == null) {
			return null;
		}
		if (nodeIds == null) {
			nodeIds = new Integer[0];
		} else {
			nodeIds = ArrayUtils.removeElement(nodeIds, nodeId);
		}
		List<NodeExt> nodeExts = node.getNodeExts();
		nodeExts.clear();
		nodeExts.add(findOrCreate(node, nodeService.get(nodeId)));
		for (Integer id : nodeIds) {
			nodeExts.add(findOrCreate(node, nodeService.get(id)));
		}
		return nodeExts;
	}
	
	@Transactional
	public List<NodeExt> update(Node node, Integer[] nodeExtIds) {
		if (nodeExtIds == null) {
			nodeExtIds = new Integer[0];
		}
		List<NodeExt> nodeExts = node.getNodeExts();
		nodeExts.clear();
		for (Integer id : nodeExtIds) {
			nodeExts.add(findOrCreate(node, nodeService.get(id)));
		}
		return nodeExts;
	}

	@Transactional
	public int moveByNodeId(Collection<Integer> nodeIds, Integer nodeId) {
		return dao.moveByNodeId(nodeIds, nodeId);
	}

	@Override
	@Transactional
	public int deleteByNodeId(Integer nodeId) {
		return dao.deleteByNodeId(nodeId);
	}

	private NodeQueryService nodeService;

	@Autowired
	public void setNodeQueryService(NodeQueryService nodeService) {
		this.nodeService = nodeService;
	}

	private NodeExtDao dao;

	@Autowired
	public void setDao(NodeExtDao dao) {
		this.dao = dao;
	}
}
